﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Utilities;
using Telerik.Web.UI;
using System.Data;
using Domain.DAL;
using Domain.Models;
using System.Drawing;
using Web;

namespace WebApp.RepairingTickets
{
    public partial class CheckWarrantyManagement : System.Web.UI.Page
    {
        #region Private Fields

        private string _preUrl = "~/RepairingTickets/CheckWarrantyManagement.aspx";
        private string _cookiesName = string.Empty;

        #endregion

        #region Private Properties

        public string CreatedDateFrom
        {
            get
            {
                if (rdpCreatedDateFrom.SelectedDate.HasValue && rdpCreatedDateFrom.SelectedDate.Value != null)
                {
                    return rdpCreatedDateFrom.SelectedDate.Value.ToString(MyConfig.DateFormat);
                }
                return string.Empty;
            }
            set
            {
                try
                {
                    rdpCreatedDateFrom.SelectedDate = DateTime.ParseExact(value, MyConfig.DateFormat, null);
                }
                catch (Exception)
                {
                    rdpCreatedDateFrom.SelectedDate = null;
                }
            }
        }

        public string CreatedDateTo
        {
            get
            {
                if (rdpCreatedDateTo.SelectedDate.HasValue && rdpCreatedDateTo.SelectedDate.Value != null)
                {
                    return rdpCreatedDateTo.SelectedDate.Value.ToString(MyConfig.DateFormat);
                }
                return string.Empty;
            }
            set
            {
                try
                {
                    rdpCreatedDateTo.SelectedDate = DateTime.ParseExact(value, MyConfig.DateFormat, null);
                }
                catch (Exception)
                {
                    rdpCreatedDateTo.SelectedDate = null;
                }
            }
        }

        #endregion

        #region RadGrid's Event Handlers

        protected void grdResult_ItemCreated(object sender, Telerik.Web.UI.GridItemEventArgs e)
        {
            try
            {
                Utility.TranslateGridPagerItem(e);
            }
            catch (Exception ex)
            {
                Utility.ShowMessageBox(this.Page, ex.ToString());
            }
        }

        protected void grdResult_ItemDataBound(object sender, GridItemEventArgs e)
        {
            try
            {
                if (e.Item.ItemType == GridItemType.AlternatingItem || e.Item.ItemType == GridItemType.Item)
                {
                    GridEditableItem editableItem = (GridEditableItem)e.Item;
                    if (editableItem != null)
                    {
                        //Format color
                        string displayColor = editableItem["DisplayColor"].Text.Trim();
                        if (!string.IsNullOrEmpty(displayColor) && displayColor != "&nbsp;")
                        {
                            editableItem.BackColor = ColorTranslator.FromHtml(displayColor);
                        }

                        //Visible check warranty
                        string checkWarranty = editableItem["IsValidWarranty"].Text.Trim();
                        string visibleCheckWarranty = editableItem["VisibleCheckWarranty"].Text.Trim();

                        if (!string.IsNullOrEmpty(visibleCheckWarranty) && !string.IsNullOrWhiteSpace(visibleCheckWarranty))
                        {
                            ImageButton imbCheckWarranty = (ImageButton)editableItem["ColCheckWarranty"].FindControl("imbCheckWarranty");
                            if (imbCheckWarranty != null)
                            {
                                imbCheckWarranty.Visible = Convert.ToBoolean(visibleCheckWarranty);

                                if (imbCheckWarranty.Visible)
                                {
                                    if (!string.IsNullOrEmpty(checkWarranty) && !string.IsNullOrWhiteSpace(checkWarranty) && checkWarranty != "&nbsp;")
                                    {
                                        if (checkWarranty == "1")
                                        {
                                            imbCheckWarranty.ImageUrl = this.ResolveUrl("~/images/ValidWarranty.gif");
                                        }
                                        else
                                        {
                                            imbCheckWarranty.ImageUrl = this.ResolveUrl("~/images/InvalidWarranty.gif");
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Utility.ShowMessageBox(this.Page, ex.ToString());
            }
        }

        protected void grdResult_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            try
            {
                BindGrid();
            }
            catch (Exception ex)
            {
                Utility.ShowMessageBox(this.Page, ex.ToString());
            }
        }

        protected void grdResult_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {
            string url = this.ResolveUrl(this._preUrl);
            try
            {
                string repairingTicketHistoryID = MyConfig.NullNumber.ToString();
                switch (e.CommandName)
                {
                    case "cmdCheckWarranty":
                        repairingTicketHistoryID = ((GridEditableItem)e.Item)["RepairingTicketHistoryID"].Text;
                        url = this.ResolveUrl("~/RepairingTickets/CheckWarrantyEdit.aspx") + "?RepairingTicketHistoryID=" + repairingTicketHistoryID + "&preUrl=" + this._preUrl;
                        Response.Redirect(url);
                        break;
                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                Utility.ShowMessageBox(this.Page, ex.ToString());
            }
        }

        protected void grdResult_PageSizeChanged(object sender, GridPageSizeChangedEventArgs e)
        {
            try
            {
                CookiesManager.Update(this._cookiesName, MyConfig.PageSizeCookiesName, e.NewPageSize.ToString());
            }
            catch (Exception ex)
            {
                Utility.ShowMessageBox(this.Page, ex.ToString());
            }
        }

        protected void grdResult_PageIndexChanged(object sender, GridPageChangedEventArgs e)
        {
            try
            {
                CookiesManager.Update(this._cookiesName, MyConfig.CurrentPageIndexCookiesName, e.NewPageIndex.ToString());
            }
            catch (Exception ex)
            {
                Utility.ShowMessageBox(this.Page, ex.ToString());
            }
        }

        #endregion

        #region Event Handlers

        protected void Page_Load(object sender, EventArgs e)
        {

            try
            {
                (Master as SiteMaster).SelectedTab = "ticketManagement";
                _cookiesName = this.GetType().Name + Session.SessionID;
                if (!IsPostBack)
                {
                    LoadForm();
                }
            }
            catch (Exception ex)
            {
                Utility.ShowMessageBox(this.Page, ex.ToString());
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            try
            {
                CookiesManager.Update(this._cookiesName, MyConfig.CurrentPageIndexCookiesName, "0");

                CookiesManager.Update(this._cookiesName, txtFullName.ID, txtFullName.Text.Trim());
                CookiesManager.Update(this._cookiesName, txtMobile.ID, txtMobile.Text.Trim());
                CookiesManager.Update(this._cookiesName, txtAddress.ID, txtAddress.Text.Trim());

                CookiesManager.Update(this._cookiesName, rcbProductType.ID, rcbProductType.SelectedValue);
                CookiesManager.Update(this._cookiesName, rcbManufacturer.ID, rcbManufacturer.SelectedValue);
                CookiesManager.Update(this._cookiesName, txtModel.ID, txtModel.Text.Trim());
                CookiesManager.Update(this._cookiesName, txtSerialNumber.ID, txtSerialNumber.Text.Trim());

                CookiesManager.Update(this._cookiesName, rdpCreatedDateFrom.ID, this.CreatedDateFrom);
                CookiesManager.Update(this._cookiesName, rdpCreatedDateTo.ID, this.CreatedDateTo);
                CookiesManager.Update(this._cookiesName, rcbRepairingType.ID, rcbRepairingType.SelectedValue);
                CookiesManager.Update(this._cookiesName, rcbStatus.ID, rcbStatus.SelectedValue);

                CookiesManager.Update(this._cookiesName, rcbWarrantyStatus.ID, rcbWarrantyStatus.SelectedValue);

                grdResult.Rebind();
            }
            catch (Exception ex)
            {
                Utility.ShowMessageBox(this.Page, ex.ToString());
            }
        }

        #endregion

        #region Private Methods

        private void BindGrid()
        {
            try
            {
                DataSet ds = new DataSet();

                //Customer information
                string fullName = txtFullName.Text.Trim();
                string mobile = txtMobile.Text.Trim();
                string address = txtAddress.Text.Trim();

                //Product information
                int productType = MyConfig.NullNumber;
                if (!string.IsNullOrEmpty(rcbProductType.SelectedValue))
                {
                    productType = Convert.ToInt32(rcbProductType.SelectedValue);
                }

                int manufacturer = MyConfig.NullNumber;
                if (!string.IsNullOrEmpty(rcbManufacturer.SelectedValue))
                {
                    manufacturer = Convert.ToInt32(rcbManufacturer.SelectedValue);
                }

                string model = txtModel.Text.Trim();
                string serialNumber = txtSerialNumber.Text.Trim();

                //Receiving & repairing information
                string createdDateFrom = this.CreatedDateFrom;
                string createdDateTo = this.CreatedDateTo;

                int repairingType = MyConfig.NullNumber;
                if (!string.IsNullOrEmpty(rcbRepairingType.SelectedValue))
                {
                    repairingType = Convert.ToInt32(rcbRepairingType.SelectedValue);
                }

                long status = MyConfig.NullNumber;
                if (!string.IsNullOrEmpty(rcbStatus.SelectedValue))
                {
                    status = Convert.ToInt64(rcbStatus.SelectedValue);
                }

                string isValidWarranty = string.Empty;
                if (!string.IsNullOrEmpty(rcbWarrantyStatus.SelectedValue))
                {
                    isValidWarranty = rcbWarrantyStatus.SelectedValue;
                }

                RepairingTicketDAO rtDAO = RepairingTicketDAO.GetInstance();
                if (rtDAO != null)
                {
                    ds = rtDAO.SearchForWarranty(fullName, mobile, address, productType, manufacturer, model, serialNumber, createdDateFrom, createdDateTo, repairingType, status, isValidWarranty);
                    grdResult.DataSource = ds;
                }

                //Get stored value from cookies
                if (CookiesManager.GetValue(this._cookiesName, MyConfig.PageSizeCookiesName) != null)
                {
                    grdResult.PageSize = Convert.ToInt32(CookiesManager.GetValue(this._cookiesName, MyConfig.PageSizeCookiesName));
                }
                if (CookiesManager.GetValue(this._cookiesName, MyConfig.CurrentPageIndexCookiesName) != null)
                {
                    grdResult.CurrentPageIndex = Convert.ToInt32(CookiesManager.GetValue(this._cookiesName, MyConfig.CurrentPageIndexCookiesName));
                }

            }
            catch (Exception)
            {
                throw;
            }
        }

        private void LoadForm()
        {
            try
            {
                this.pageTitle.Text = Resources.Strings.TicketManagement + @"\" + Resources.Strings.CheckWarranty;

                BindProductTypes();
                BindManufacturers();
                BindRepairingTypes();
                BindStatus();

                rcbRepairingType.SelectedValue = GetParameterValue(MyConfig.RepairingTypeIsWarrantyIDCode);
                StatusDAO sDAO = StatusDAO.GetInstance();
                if(sDAO != null)
                {
                    Status s = sDAO.GetEndStatus();
                    if (s != null)
                    {
                        rcbStatus.SelectedValue = s.ID.ToString();
                    }
                }
                this.CreatedDateTo = DateTime.Now.ToString(MyConfig.DateFormat);
                this.CreatedDateFrom = DateTime.Now.AddDays(Convert.ToInt32(GetParameterValue(MyConfig.ReceivingDateAgoCode))).ToString(MyConfig.DateFormat);

                //Get stored value from cookies
                if (CookiesManager.GetValue(this._cookiesName, txtFullName.ID) != null)
                {
                    txtFullName.Text = CookiesManager.GetValue(this._cookiesName, txtFullName.ID);
                }
                if (CookiesManager.GetValue(this._cookiesName, txtMobile.ID) != null)
                {
                    txtMobile.Text = CookiesManager.GetValue(this._cookiesName, txtMobile.ID);
                }
                if (CookiesManager.GetValue(this._cookiesName, txtAddress.ID) != null)
                {
                    txtAddress.Text = CookiesManager.GetValue(this._cookiesName, txtAddress.ID);
                }
                if (CookiesManager.GetValue(this._cookiesName, rcbProductType.ID) != null)
                {
                    rcbProductType.SelectedValue = CookiesManager.GetValue(this._cookiesName, rcbProductType.ID);
                }
                if (CookiesManager.GetValue(this._cookiesName, rcbManufacturer.ID) != null)
                {
                    rcbManufacturer.SelectedValue = CookiesManager.GetValue(this._cookiesName, rcbManufacturer.ID);
                }
                if (CookiesManager.GetValue(this._cookiesName, txtModel.ID) != null)
                {
                    txtModel.Text = CookiesManager.GetValue(this._cookiesName, txtModel.ID);
                }
                if (CookiesManager.GetValue(this._cookiesName, txtSerialNumber.ID) != null)
                {
                    txtSerialNumber.Text = CookiesManager.GetValue(this._cookiesName, txtSerialNumber.ID);
                }
                if (CookiesManager.GetValue(this._cookiesName, rdpCreatedDateFrom.ID) != null)
                {
                    this.CreatedDateFrom = CookiesManager.GetValue(this._cookiesName, rdpCreatedDateFrom.ID);
                }
                if (CookiesManager.GetValue(this._cookiesName, rdpCreatedDateTo.ID) != null)
                {
                    this.CreatedDateTo = CookiesManager.GetValue(this._cookiesName, rdpCreatedDateTo.ID);
                }
                if (CookiesManager.GetValue(this._cookiesName, rcbRepairingType.ID) != null)
                {
                    rcbRepairingType.SelectedValue = CookiesManager.GetValue(this._cookiesName, rcbRepairingType.ID);
                }
                if (CookiesManager.GetValue(this._cookiesName, rcbStatus.ID) != null)
                {
                    rcbStatus.SelectedValue = CookiesManager.GetValue(this._cookiesName, rcbStatus.ID);
                }
                if (CookiesManager.GetValue(this._cookiesName, rcbWarrantyStatus.ID) != null)
                {
                    rcbWarrantyStatus.SelectedValue = CookiesManager.GetValue(this._cookiesName, rcbWarrantyStatus.ID);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        private void BindRepairingTypes()
        {
            DataSet ds = new DataSet();
            try
            {
                RepairingTypeDAO daoObject = RepairingTypeDAO.GetInstance();
                RepairingType rt = new RepairingType();

                ds = daoObject.Search(rt);
                if (ds != null)
                {
                    Utility.BindRadComboBox(rcbRepairingType, ds, "RepairingTypeName", "ID", true);
                }
            }
            catch (Exception)
            {
                ds.Dispose();
                throw;
            }
        }

        private void BindProductTypes()
        {
            DataSet ds = new DataSet();
            try
            {
                ProductTypeDAO daoObject = ProductTypeDAO.GetInstance();
                ProductType pt = new ProductType();

                ds = daoObject.Search(pt);
                if (ds != null)
                {
                    Utility.BindRadComboBox(rcbProductType, ds, "ProductTypeName", "ID", true);
                }
            }
            catch (Exception)
            {
                ds.Dispose();
                throw;
            }
        }

        private void BindManufacturers()
        {
            DataSet ds = new DataSet();
            try
            {
                ManufacturerDAO daoObject = ManufacturerDAO.GetInstance();
                Manufacturer m = new Manufacturer();

                ds = daoObject.Search(m);
                if (ds != null)
                {
                    Utility.BindRadComboBox(rcbManufacturer, ds, "Name", "ID", true);
                }
            }
            catch (Exception)
            {
                ds.Dispose();
                throw;
            }
        }

        private void BindStatus()
        {
            DataSet ds = new DataSet();
            try
            {
                StatusDAO daoObject = StatusDAO.GetInstance();
                Status s = new Status();

                ds = daoObject.Search(s);
                if (ds != null)
                {
                    Utility.BindRadComboBox(rcbStatus, ds, "StatusName", "ID", true);
                }
            }
            catch (Exception)
            {
                ds.Dispose();
                throw;
            }
        }

        private string GetParameterValue(string code)
        {
            string value = string.Empty;
            try
            {
                Domain.DAL.ParameterDAO pDAO = Domain.DAL.ParameterDAO.GetInstance();
                if (pDAO != null)
                {
                    Domain.Models.Parameter p = new Domain.Models.Parameter();

                    p = pDAO.GetByCode(code);
                    if (p != null && !string.IsNullOrEmpty(p.Value))
                    {
                        value = p.Value;
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
            return value;
        }

        #endregion

    }
}